#!/usr/bin/python
#
# Copyright (c) 2010, Takashi Ito
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. Neither the name of the authors nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import re

from trac.core import *

from trac.config import Option
from trac.util.html import html
from trac.mimeview import Context

from trac.web.chrome import INavigationContributor
from trac.web.chrome import ITemplateProvider
from trac.web.main import IRequestHandler
from trac.attachment import ILegacyAttachmentPolicyDelegate

from testmanagement.api import TestManagementSystem


class TestManagementModule(Component):

    implements(ILegacyAttachmentPolicyDelegate, ITemplateProvider,
               INavigationContributor, IRequestHandler)

    title = Option('testmanagement', 'title', 'Test',
                   'Main navigation bar button title.')

    _perm_maps = {
        'ATTACHMENT_CREATE': {
            'test': 'TEST_EDIT',
        },
        'ATTACHMENT_VIEW': {
            'test': 'TEST_VIEW',
        },
        'ATTACHMENT_DELETE': {
            'test': 'TEST_DELETE',
        },
    }

    # ILegacyAttachmentPolicyDelegate
    def check_attachment_permission(self, action, username, resource, perm):
        perm_map = self._perm_maps.get(action)
        if not perm_map or not resource or resource.realm != 'attachment':
            return 
        legacy_action = perm_map.get(resource.parent.realm)
        if legacy_action:
            return perm.has_permission(legacy_action)

    # ITemplateProvider methods
    def get_htdocs_dirs(self):
        from pkg_resources import resource_filename
        return [('test', resource_filename(__name__, 'htdocs'))]

    def get_templates_dirs(self):
        from pkg_resources import resource_filename
        return [resource_filename(__name__, 'templates')]

    # INavigationContributor methods
    def get_active_navigation_item(self, req):
        return 'Test'

    def get_navigation_items(self, req):
        if req.perm.has_permission('TEST_VIEW'):
            yield 'mainnav', 'Test', html.a(self.title, href=req.href.test())

    # IRequestHandler methods
    def match_request(self, req):
        if req.path_info == '/test':
            req.args['action'] = 'projects'
            return True
        if req.path_info == '/test/newproject':
            req.args['action'] = 'newproject'
            return True

        match = re.match(r'/test/(?P<action>spec|customfield)/(?P<id>[0-9]+)$', req.path_info)
        if match:
            req.args['action'] = match.group('action')
            req.args['id'] = match.group('id')
            return True

        match = re.match(r'/test/(?P<id>[0-9]+)$', req.path_info)
        if match:
            req.args['id'] = match.group('id')
            if 'root' in req.args:
                req.args['action'] = 'tree'
                # when ?root=source
                root = req.args.get('root')
                if root != 'source':
                    req.args['id'] = root
            else:
                req.args['action'] = 'detail'
            return True

        regex = r'/test/(?P<id>[0-9]+)/(?P<action>newsuite|newtestcase|part|customfields|newcustomfield)$'
        match = re.match(regex, req.path_info)
        if match:
            req.args['action'] = match.group('action')
            req.args['id'] = match.group('id')
            return True

    def process_request(self, req):
        #print '$$$$ %s - %s' % (req.args.get('action'), req.args.get('id'))
        # Create request context
        #context = Context.from_request(req)('testmanagement', id=req.args.get('id'))

        # Process request and return content
        api = self.env[TestManagementSystem]
        return api.process(req)

